<template>
	<div>
		<el-form ref="form" :rules="rules" :model="form" label-width="80px">
			<el-form-item prop="username" label="用户名" required>
				<el-input v-model="form.username" placeholder="用户名"></el-input>
			</el-form-item>
			<el-form-item prop="password" label="密码" required>
				<el-input
					v-model="form.password"
					type="password"
					placeholder="密码"
				></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="submit"> 登录 </el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
import { checkUsername, checkPassword } from '@/tools/reg'
import { getMenus } from '@/api/rights'
import createRouter from '@/router/mainRouter'
// @vuese
// @group 登录
export default {
	data() {
		var checkU = (rule, value, callback) => {
			return callback()
			if (checkUsername(value)) {
				callback()
			} else {
				callback(new Error('账户不符合规范！'))
			}
		}
		var checkP = (rule, value, callback) => {
			if (checkPassword(value)) {
				callback()
			} else {
				callback(new Error('密码不符合规范！'))
			}
		}
		return {
			form: {
				username: 'admin',
				password: '123456',
			},
			rules: {
				username: [{ validator: checkU, trigger: 'blur' }],
				password: [{ validator: checkP, trigger: 'blur' }],
			},
		}
	},
	methods: {
		/* 
		 @vuese
		 登录
		 @arg  username password
		*/
		submit() {
			// 先前端校验
			this.$refs.form.validate((state) => {
				if (!state) {
					return
				}

				// 登录之后立即发起请求获取左侧菜单
				var login = new Promise((resolve, reject) => {
					this.$store.dispatch('LOGIN', this.form).then((res) => {
						resolve(true)
					})
				})

				login.then((state) => {
					getMenus().then(({ data }) => {
						// 先把菜单的数据存入本地
						sessionStorage.setItem('menus', JSON.stringify(data.data))
						// 根据数据生成路由--动态添加路由
						createRouter(data.data, this.$router)
						this.$router.replace('/main')
					})
				})
			})
		},
	},
}
</script>

<style>
</style>